package com.lcy.proto.client;

import com.google.protobuf.*;
import com.lcy.proto.rpc.Params;
import com.lcy.proto.rpc.RequestWrapper;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author loucy
 * @version 1.0
 */
public class ClientBlockingRpcChannel implements BlockingRpcChannel {
    private SocketChannel channel;

    public ClientBlockingRpcChannel(String host,int port) throws IOException {
        channel = SocketChannel.open();
        channel.socket().connect(new InetSocketAddress(host,port));
    }
    @Override
    public Message callBlockingMethod(Descriptors.MethodDescriptor method, RpcController controller, Message request, Message responsePrototype) throws ServiceException {
        RequestWrapper wrapper = RequestWrapper.newBuilder()
                .setService(method.getService().getFullName())
                .setMethod(method.getName())
                .setParams((Params) request)
                .build();

        byte[] bytes = wrapper.toByteArray();
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        buffer.put(bytes);
        buffer.flip();
        try {
            channel.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ByteBuffer receive = ByteBuffer.allocate(1024);
        try {
            channel.read(receive);
            receive.flip();
            byte[] resultBytes = new byte[receive.limit()];
            receive.get(resultBytes);
            return responsePrototype.toBuilder()
                    .mergeFrom(resultBytes)
                    .build();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
